package chapter01_Arr

/**
 * Created with IntelliJ IDEA.
 * ClassName: Test07_Map
 * Package: chapter01_Arr
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 *          Date: 2023-07-14
 *          Time: 22:48
 */

object Test07_Map {
  def main(args: Array[String]): Unit = {
    //创建不可变Map
    val map1: Map[String, Int] = Map("a" -> 12, "b" -> 23, "c" -> 34, "hello" -> 99)
    println(map1) //Map(a -> 12, b -> 23, c -> 34, hello -> 99)
    println(map1.getClass) //class scala.collection.immutable.Map$Map4
    //$ 可变 Map4 4个元素

    //(a,12)
    //(b,23)
    //(c,34)
    //(hello,99)

    //遍历元素
    map1.foreach(println)
    println("-------------------")
    map1.foreach((kv: (String, Int)) => println(kv))

    //和上面遍历效果一样
    for (elem <- map1) {
      println(elem)
    }

    println("---迭代器遍历---")
    //效果等同
    val iterator = map1.iterator
    while (iterator.hasNext) {
      println(iterator.next())
    }

    println("-------------")
    //访问元素 获取Map中所有的key
    for (key <- map1.keys) {
      println(key + "------" + map1.get(key))
      //map1.get(key) 获取对应的元素  Some(12)
    }

    println(map1.get("a").get) //12
    println(map1.get("c")) //None 如果在调用get那么就是空指针异常 Some(34)
    println(map1.getOrElse("c",0)) //如果没有对应的val值 那么就输出默认值
    println(map1("a")) //12 要是没有元素直接抛异常


  }
}
